import 'package:flutter/material.dart';
import 'package:flutter_app/app/models/movie.dart';
import 'package:flutter_app/config/sites.dart';
import 'package:flutter_app/resources/pages/play_page.dart';
import 'package:flutter_app/resources/widgets/image.dart';
import 'package:flutter_app/resources/widgets/search_input_widget.dart';
import 'package:nylo_framework/nylo_framework.dart';
import '/app/controllers/search_movie_controller.dart';
import 'package:flutter/cupertino.dart';

class SearchMoviePage extends NyStatefulWidget<SearchMovieController> {
  static RouteView path = ("/search-movie", (_) => SearchMoviePage());

  SearchMoviePage({super.key}) : super(child: () => _SearchMoviePageState());
}

class _SearchMoviePageState extends NyPage<SearchMoviePage> {
  /// [SearchMovieController] controller
  SearchMovieController get controller => widget.controller;
  final FocusNode _searchFocusNode = FocusNode();

  List<SiteMovies> searchResults = [];
  int _selectedIndex = 0;
  String query = "";

  @override
  get init => () async {
        String? query = widget.data();
        if (query != "") {
          setState(() {
            this.query = query!;
          });
          // 遍历API_SITES， 构造SearchResults
          searchResults.addAll(API_SITES.map(
              (site) => SiteMovies(data: [], site: site["name"]!.toString())));
        }
      };

  @override
  void dispose() {
    _searchFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget view(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Padding(
          padding: EdgeInsets.only(right: 20),
          child: SearchInput(
            searchFocusNode: _searchFocusNode,
            query: query,
          ),
        ),
        titleSpacing: 0,
        backgroundColor: Theme.of(context).appBarTheme.backgroundColor,
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: searchResults.isEmpty
                  ? Center(
                      child: Text(
                        "暂无资源",
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    )
                  : Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Left side - Site list
                        Expanded(
                          flex: 2,
                          child: Left(),
                        ),
                        // Right side - Movie data
                        Expanded(
                          flex: 5,
                          child: Right(),
                        ),
                      ],
                    ),
            ),
          ],
        ),
      ),
    );
  }

  Widget Left() {
    return Container(
      padding: EdgeInsets.only(top: 4),
      color: Colors.grey[50],
      child: ListView.builder(
        shrinkWrap: true,
        itemCount: searchResults.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              setState(() {
                _selectedIndex = index;
              });
            },
            child: Container(
              margin: EdgeInsets.all(4),
              padding: EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: _selectedIndex == index
                    ? Colors.grey[200]
                    : Colors.grey[100],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                searchResults[index].site,
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: _selectedIndex == index
                      ? FontWeight.bold
                      : FontWeight.normal,
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget Right() {
    return NyPullToRefresh(
      key: ValueKey(_selectedIndex),
      footerLoadingIcon: CupertinoActivityIndicator(),
      empty: Center(child: Text("暂无资源")),
      loadingStyle: LoadingStyle.normal(
        child: Center(
          child: CupertinoActivityIndicator(),
        ),
      ),
      child: (context, movie) {
        movie as MoviesList;
        return GestureDetector(
          onTap: () {
            routeTo(PlayPage.path, data: movie);
          },
          child: Card(
            elevation: 0,
            margin: EdgeInsets.all(8),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Image section
                ClipRRect(
                  borderRadius: BorderRadius.horizontal(
                    left: Radius.circular(8),
                  ),
                  child: Container(
                    width: 100,
                    height: 150,
                    child: ImageWidget(
                      imageUrl: movie.vodPic ?? '',
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                // Text info section
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(8),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          movie.vodName ?? '无标题',
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 4),
                        Text(
                          '评分: ${movie.vodDoubanScore ?? '0.0'}',
                          style: TextStyle(
                            color: Theme.of(context).primaryColor,
                            fontSize: 12,
                          ),
                        ),
                        if (movie.vodYear != null)
                          Padding(
                            padding: const EdgeInsets.only(top: 4),
                            child: Text(
                              '年份: ${movie.vodYear}',
                              style: TextStyle(fontSize: 12),
                            ),
                          ),
                        if (movie.vodRemarks != null)
                          Padding(
                            padding: const EdgeInsets.only(top: 4),
                            child: Text(
                              '更新: ${movie.vodRemarks}',
                              style: TextStyle(fontSize: 12),
                            ),
                          ),
                        if (movie.vodLang != null)
                          Padding(
                            padding: const EdgeInsets.only(top: 4),
                            child: Text(
                              '语言: ${movie.vodLang}',
                              style: TextStyle(fontSize: 12),
                            ),
                          ),
                        if (movie.vodClass != null)
                          Padding(
                            padding: const EdgeInsets.only(top: 4),
                            child: Text(
                              '类型: ${movie.vodClass}',
                              style: TextStyle(fontSize: 12),
                            ),
                          ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
      data: (int iteration) async {
        Movies movies = await widget.controller.searchMovie(
            API_SITES[_selectedIndex]["api"]!.toString(), query, iteration);
        return movies.list;
      },
    );
  }
}
